/**
 * Created by Heycz on 2015/9/23.
 */
appModule.directive("appMap", function () {
  return {
    restrict: "E",
    replace: true,
    template: "<div id='allMap'></div>",
    scope: {
      center: "=",		// Center point on the map (e.g. <code>{ latitude: 10, longitude: 10 }</code>).
      markers: "=",	   // Array of map markers (e.g. <code>[{ lat: 10, lon: 10, name: "hello" }]</code>).
      width: "@",		 // Map width in pixels.
      height: "@",		// Map height in pixels.
      zoom: "@",		  // Zoom level (one is totally zoomed out, 25 is very much zoomed in).
      zoomControl: "@",   // Whether to show a zoom control on the map.
      scaleControl: "@",   // Whether to show scale control on the map.
      address: "="
    },
    link: function (scope, element, attrs) {
      var h1 = document.getElementsByTagName('ion-content')[0].clientHeight;
      var h2 = document.getElementsByTagName('ion-tabs')[0].children[0].clientHeight;
      var height = h1 + h2;
      element.css('height', height + 'px');
      // 百度地图API功能
      var map = new BMap.Map("allMap");
      map.addControl(new BMap.ZoomControl());
      // 创建地址解析器实例
      var myGeo = new BMap.Geocoder();
      var myGeolocation = new BMap.Geocoder();
      scope.$watch(scope.address, function (newValue, oldValue) {
        // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint(scope.address, function (point) {
          if (point) {
            map.centerAndZoom(point, 16);
            map.addOverlay(new BMap.Marker(point));
          } else {
            alert('无法解释位置:' + scope.address);
            myGeolocation.getCurrentPosition(function (result) {
              map.centerAndZoom(result.point, 16);
              map.addOverlay(new BMap.Marker(result.point));
            });
          }
        }, "");
      });
    }
  };
})
  .directive('lazyScroll', ['$rootScope', '$timeout',
    function ($rootScope, $timeout) {
      return {
        restrict: 'A',
        link: function ($scope, $element) {

          var scrollTimeoutId = 0;

          $scope.invoke = function () {
            $rootScope.$broadcast('lazyScrollEvent');
          };

          $element.bind('scroll', function () {

            $timeout.cancel(scrollTimeoutId);

            // wait and then invoke listeners (simulates stop event)
            scrollTimeoutId = $timeout($scope.invoke, 150);

          });


        }
      };
    }])

  .directive('imageLazySrc', ['$document', '$timeout', '$ionicScrollDelegate', '$compile',
    function ($document, $timeout, $ionicScrollDelegate, $compile) {
      return {
        restrict: 'A',
        scope: {
          lazyScrollResize: "@lazyScrollResize",
          imageLazyBackgroundImage: "@imageLazyBackgroundImage",
          imageLazySrc: "@"
        },
        link: function ($scope, $element, $attributes) {
          if (!$attributes.imageLazyDistanceFromBottomToLoad) {
            $attributes.imageLazyDistanceFromBottomToLoad = 0;
          }
          if (!$attributes.imageLazyDistanceFromRightToLoad) {
            $attributes.imageLazyDistanceFromRightToLoad = 0;
          }

          var loader;
          if ($attributes.imageLazyLoader) {
            loader = $compile('<div class="image-loader-container"><ion-spinner class="image-loader" icon="' + $attributes.imageLazyLoader + '"></ion-spinner></div>')($scope);
            $element.after(loader);
          }

          $scope.$watch('imageLazySrc', function (oldV, newV) {
            if (loader)
              loader.remove();
            if ($attributes.imageLazyLoader) {
              loader = $compile('<div class="image-loader-container"><ion-spinner class="image-loader" icon="' + $attributes.imageLazyLoader + '"></ion-spinner></div>')($scope);
              $element.after(loader);
            }
            var deregistration = $scope.$on('lazyScrollEvent', function () {
                console.log('scroll');
                if (isInView()) {
                  loadImage();
                  deregistration();
                }
              }
            );
            $timeout(function () {
              if (isInView()) {
                loadImage();
                deregistration();
              }
            }, 500);
          });
          var deregistration = $scope.$on('lazyScrollEvent', function () {
              console.log('scroll');
              if (isInView()) {
                loadImage();
                deregistration();
              }
            }
          );

          function loadImage() {
            //Bind "load" event
            $element.bind("load", function (e) {
              if ($attributes.imageLazyLoader) {
                loader.remove();
              }
              if ($scope.lazyScrollResize == "true") {
                //Call the resize to recalculate the size of the screen
                $ionicScrollDelegate.resize();
              }
              $element.unbind("load");
            });

            if ($scope.imageLazyBackgroundImage == "true") {
              var bgImg = new Image();
              bgImg.onload = function () {
                if ($attributes.imageLazyLoader) {
                  loader.remove();
                }
                $element[0].style.backgroundImage = 'url(' + $attributes.imageLazySrc + ')'; // set style attribute on element (it will load image)
                if ($scope.lazyScrollResize == "true") {
                  //Call the resize to recalculate the size of the screen
                  $ionicScrollDelegate.resize();
                }
              };
              bgImg.src = $attributes.imageLazySrc;
            } else {
              $element[0].src = $attributes.imageLazySrc; // set src attribute on element (it will load image)
            }
          }

          function isInView() {
            var clientHeight = $document[0].documentElement.clientHeight;
            var clientWidth = $document[0].documentElement.clientWidth;
            var imageRect = $element[0].getBoundingClientRect();
            return (imageRect.top >= 0 && imageRect.top <= clientHeight + parseInt($attributes.imageLazyDistanceFromBottomToLoad))
              && (imageRect.left >= 0 && imageRect.left <= clientWidth + parseInt($attributes.imageLazyDistanceFromRightToLoad));
          }

          // bind listener
          // listenerRemover = scrollAndResizeListener.bindListener(isInView);

          // unbind event listeners if element was destroyed
          // it happens when you change view, etc
          $element.on('$destroy', function () {
            deregistration();
          });

          // explicitly call scroll listener (because, some images are in viewport already and we haven't scrolled yet)
          $timeout(function () {
            if (isInView()) {
              loadImage();
              deregistration();
            }
          }, 500);
        }
      };
    }]);
;
